// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain , dialog} = require('electron')
const path = require('path');
// const java = require('./java');
// const pg = require('./pgManager');

const { hasPostgreSQL, promptInstall } = require('./checkPostgres');

const { startPythonServices, stopPythonServices } = require('./py-services');

// 抑制主进程未捕获异常的系统弹框，改为仅打印日志
process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception:', error);
});
process.on('unhandledRejection', (reason) => {
  console.error('Unhandled Rejection:', reason);
});
// 可选：彻底禁止 showErrorBox 弹窗
try { require('electron').dialog.showErrorBox = () => {}; } catch {}




async function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    // frame:false,
    webPreferences: {
      // webSecurity: false,
      nodeIntegration: true,
      contextIsolation: false,
      contentSecurityPolicy: "default-src 'self'; script-src 'self' 'unsafe-inline'",
      preload: path.join(__dirname, 'preload.js')
    }
  })

    // 1. 检测 PostgreSQL
  const ok = await hasPostgreSQL();
  if (!ok) {
    await promptInstall(win);
    app.quit();          // 或者允许用户继续，但禁用某些功能
    return;
  }

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')
  // mainWindow.setMenu(false);
  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
  // ipcMain.on('open-file-dialog', () => {
  //   const result = dialog.showOpenDialogSync(mainWindow, {
  //     title: '选择文件',
  //     properties: ['openFile']
  //   });

  //   if (result) {
  //     const { filePaths } = result;
  //     if (filePaths.length > 0) {
  //       mainWindow.webContents.send('selected-file-path', filePaths[0]);
  //     }
  //   } else {
  //     // 用户取消了对话框
  //     mainWindow.webContents.send('file-dialog-cancelled');
  //   }
  // });
  ipcMain.on('open-folder-dialog', async () => {
    const mainWindow = BrowserWindow.getFocusedWindow();
    let filePaths = await dialog.showOpenDialog(mainWindow, {
      title: '选择文件夹',
      properties: ['openDirectory', 'createDirectory']
    });
    console.log(filePaths)
    console.log(filePaths.filePaths.length)
    if (filePaths.filePaths.length > 0) {
      const folderPath = filePaths.filePaths[0]; // 获取选择的文件夹路径
      // 将文件夹路径发送到渲染进程
      mainWindow.webContents.send('selected-folder-path', folderPath);
    }
  });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  // 仅在打包环境尝试启动 PG，且兼容 pg/postgres 目录名
  if (app.isPackaged) {
    try {
      // 优先尝试 resources/pg/start.js，如果不存在则尝试 resources/postgres/start.js
      try { require('./resources/pg/start.js'); }
      catch {
        require('./resources/postgres/start.js');
      }
    } catch (e) {
      console.error('Postgres start error:', e);
    }
  }

  // await pg.start();    

  // 启动 Python 后端服务（analysis、case、dp）
  startPythonServices();



  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', async function () {
  // await pg.stop();
  stopPythonServices();
  if (process.platform !== 'darwin') app.quit()
})

app.on('before-quit', async () => {
  // await pg.stop();
  stopPythonServices();
});

app.on('will-quit', async () => {
  // await pg.stop();
  stopPythonServices();
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
